package com.xxx.chat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) {

		ServerSocket serverSocket = null;

		Socket accept = null;

		InputStream inputStream = null;

		BufferedInputStream bis = null;

		BufferedOutputStream bos = null;

		OutputStream outputStream = null;

		System.out.println("------------------------服务端---------------------------");

		try {
			//1. 创建未绑定的服务器套接字。			指定端口的服务器套接字
			serverSocket = new ServerSocket(8848);

			//2. 监听服务端
			accept = serverSocket.accept();

			//3. 在客户端中已经将信息发送至服务端，现在需要接收
			inputStream = accept.getInputStream();

			bis = new BufferedInputStream(inputStream);
//
			byte[] b = new byte[1024];
//			int len;
//			while((len = bis.read(b)) != -1) {
//
			bis.read(b);
			System.out.println(new String(b));

//			}

			//4. 服务端接收到信息后回话
			outputStream = accept.getOutputStream();

			bos = new BufferedOutputStream(outputStream);
			String msg = "hi!";
			b = msg.getBytes();
			bos.write(b);
			bos.flush();


		} catch (IOException e) {
			e.printStackTrace();
		}finally {

				try {
					if (bos != null) {
						bos.close();
					}
					if (bis != null) {
						bis.close();
					}

					if (outputStream != null) {
						outputStream.close();
					}

					if (inputStream != null) {
						inputStream.close();
					}
					if (accept != null) {
						accept.close();
					}
					if (serverSocket != null) {
						serverSocket.close();
					}

				} catch (IOException e) {
					e.printStackTrace();
				}



		}

	}

}


